<template>
  <div class="w-e-container" ref="w-e-container">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editorId="editorId"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 300px"
      :editorId="editorId"
      :defaultConfig="editorConfig"
      :defaultContent="getDefaultContent"
      @onChange="onChange"
      @onCreated="onCreated"
      @onBlur="onBlur"
      :mode="mode"
    />
  </div>
</template>
<script>
import {
  Editor,
  Toolbar,
  getEditor,
  removeEditor
} from '@wangeditor/editor-for-vue'
import cloneDeep from 'lodash.clonedeep'
import request from '@/utils/request'
import { getUrl, getSign } from '@/utils/request/sign'
import emitter from 'fawkes-lib/src/mixins/emitter'
export default {
  components: { Editor, Toolbar },
  mixins: [emitter],
  inject: {
    fksForm: {
      default: ''
    },
    fksFormItem: {
      default: ''
    }
  },
  props: {
    value: {
      // type: String,
      default() {
        return JSON.stringify([])
      }
    },
    readonly: {
      type: Boolean,
      default: false
    },
    html: {
      default: ''
    }
  },

  data() {
    return {
      editorId: `w-e-${Math.random().toString().slice(-5)}`, //【注意】编辑器 id ，要全局唯一
      toolbarConfig: { excludeKeys: [] },
      editorConfig: {
        // readOnly: false,
        placeholder: '请输入内容...',
        // autoFocus: true,
        MENU_CONF: {
          uploadImage: {
            // 自定义上传
            customUpload(file, insertFn) {
              let formData = new FormData()
              formData.append('file', file)
              request({
                url: '/sys-storage/upload',
                method: 'post',
                headers: {
                  'Content-Type': 'multipart/form-data'
                },
                params: getSign(),
                data: formData,
                timeout: 0
              })
                .then((res) => {
                  const fileName = res.data.fileName
                  const fileToken = res.data.fileToken
                  const downloadUrl =
                    process.env.VUE_APP_BASE_PATH + 'api/sys-storage/download?'
                  const url = getUrl({ f8s: fileToken })
                  const fullUrl = downloadUrl + url
                  // console.log(url)
                  insertFn(fullUrl, fileName, fullUrl)
                })
                .catch((err) => {
                  console.log(err)
                })
              // file 即选中的文件
              // 自己实现上传，并得到图片 url alt href
              // 最后插入图片
            }
          }
        }
      },
      mode: 'simple' // or 'simple'
    }
  },
  computed: {
    readonlyIn() {
      return (
        this.readonly ||
        (this.fksForm || {}).readonly ||
        (this.fksFormItem || {}).readonly
      )
    },
    getDefaultContent() {
      return cloneDeep(JSON.parse(this.value)) //【注意】深度拷贝 value ，否则会报错
    }
  },
  watch: {
    //只读通过改变dom元素的contenteditable来控制
    readonlyIn(val) {
      this.setReadonly(val)
    }
  },
  created() {},
  mounted() {
    this.setReadonly(this.readonlyIn)
  },
  methods: {
    onCreated() {
      // const editor = getEditor(this.editorId)
      // this.editor = editor
    },
    onChange(editor) {
      const value = editor.children
      this.$emit('input', JSON.stringify(value))
      this.$emit('update:html', editor.getHtml())
      this.dispatch('FksFormItem', 'fks.form.change')
    },
    onBlur() {
      this.dispatch('FksFormItem', 'fks.form.blur')
    },
    setReadonly(val) {
      let contentBox = this.$refs['w-e-container'].querySelector(
        '[data-slate-editor]'
      )
      contentBox.setAttribute('contenteditable', !val)
    }
  },
  beforeDestroy() {
    // const editor = getEditor(this.editorId)
    // console.log(editor)
    // if (editor == null) return
    // // 【注意】组件销毁时，及时销毁编辑器
    // editor.destroy()
    // removeEditor(this.editorId)
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.w-e-container {
  border: 1px solid #ccc;
}
::v-deep .w-e-text-placeholder {
  top: 9px;
  left: 16px;
}
</style>
